import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:base_flutter/base_flutter.dart';

class FunctionGridList extends StatelessWidget {
  List<Widget> children = [];
  int count;
  num crossSpace = 0;
  num mainSpace = 0;
  Widget? mainDivider;
  ScrollController? controller;
  List<List<Widget>> _itemList = [];
  EdgeInsets? padding;

  FunctionGridList(
      {required this.children,
        required this.count,
        this.crossSpace = 0,
        this.mainSpace = 0,
        this.padding,
        this.mainDivider,this.controller}) {
    _itemList = chunkList(children, count);
  }

  @override
  Widget build(BuildContext context) {
    return ListView(
      padding: padding,
      controller: controller,
      children: _itemList
          .map((e) {
        var list = <Widget>[];
        list.addAll(e);

        while (list.length < count) {
          list.add(Container());
        }
        return Row(
          children: list
              .map((widget) => widget.setWeight(1))
              .toList()
              .insertWidget(SizedBox(
            width: crossSpace.toDouble(),
          )),
        );
      })
          .toList()
          .insertWidget(mainDivider ??
          SizedBox(
            height: mainSpace.toDouble(),
          )),
    );
  }

  List<List<Widget>> chunkList(List<Widget> list, int chunkSize) {
    final List<List<Widget>> chunks = [];
    for (var i = 0; i < list.length; i += chunkSize) {
      final int end = min(i + chunkSize, list.length);
      chunks.add(list.sublist(i, end));
    }
    return chunks;
  }
}


class FunctionGridColumn extends StatelessWidget {
  List<Widget> children = [];
  int count;
  num crossSpace = 0;
  num mainSpace = 0;
  Widget? mainDivider;

  List<List<Widget>> _itemList = [];

  FunctionGridColumn(
      {required this.children,
        required this.count,
        this.crossSpace = 0,
        this.mainSpace = 0,
        this.mainDivider}) {
    _itemList = chunkList(children, count);
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: _itemList
          .map((e) {
        var list = <Widget>[];
        list.addAll(e);

        while (list.length < count) {
          list.add(Container());
        }
        return Row(
          children: list
              .map((widget) => widget.setWeight(1))
              .toList()
              .insertWidget(SizedBox(
            width: crossSpace.toDouble(),
          )),
        );
      })
          .toList()
          .insertWidget(mainDivider ??
          SizedBox(
            height: mainSpace.toDouble(),
          )),
    );
  }

  List<List<Widget>> chunkList(List<Widget> list, int chunkSize) {
    final List<List<Widget>> chunks = [];
    for (var i = 0; i < list.length; i += chunkSize) {
      final int end = min(i + chunkSize, list.length);
      chunks.add(list.sublist(i, end));
    }
    return chunks;
  }
}